package ngames.com.sushitv.action;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import ngames.com.sushitv.R;
import ngames.com.sushitv.activity.ResetPasswordActivity;
import ngames.com.sushitv.base.BaseAction;
import ngames.com.sushitv.core.ModelCallback;
import ngames.com.sushitv.entity.ResetPasswordInfo;
import ngames.com.sushitv.tools.AppUtil;
import ngames.com.sushitv.tools.Code;
import ngames.com.sushitv.tools.Constants;

/**
 * Created by Jeffrey on 2016/8/4.
 */
public class ForgotPasswordAction extends BaseAction implements View.OnClickListener {
    private static final String FORGOT_TYPE_EMAIL = "1";
    private static final String FORGOT_TYPE_PHONE = "2";

    private LinearLayout mEmailFrom;
    private LinearLayout mPhoneFrom;
    private ImageView mCaptchaImv;
    private EditText mEmailEdt;
    private EditText mCaptchaEdt;
    private TextView mResetHintTv;
    private EditText mPhoneEdt;
    private Button mSendBtn;
    private Code mCode;
    private SendSmsAction mSendSmsAction;
    private String mCaptchaCode;
    private String mForgotType;

    public ForgotPasswordAction(Activity activity, View baseView) {
        super(activity, baseView);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        View baseView = mBaseView;
        setTitle(R.string.title_forgot_password);
        mEmailFrom = (LinearLayout) baseView.findViewById(R.id.forgot_email_form);
        mPhoneFrom = (LinearLayout) baseView.findViewById(R.id.base_layout_sms);
        mPhoneFrom.setVisibility(View.GONE);

        mEmailEdt = (EditText) findViewById(R.id.email);
        mCaptchaEdt = (EditText) findViewById(R.id.edt_captcha);
        mResetHintTv = (TextView) findViewById(R.id.tev_reset_hint);
        mCaptchaImv = (ImageView) findViewById(R.id.imv_captcha);
        mCaptchaImv.setOnClickListener(this);
        setCaptchaImv();

        mPhoneEdt = (EditText) baseView.findViewById(R.id.pr_edt_phone);

        mSendBtn = (Button) findViewById(R.id.btn_send);
        mSendBtn.setOnClickListener(this);
        mForgotType = FORGOT_TYPE_EMAIL;
        RadioGroup titleButton = (RadioGroup) findViewById(R.id.rdg_title_bar);
        titleButton.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rbt_email:
                        mForgotType = FORGOT_TYPE_EMAIL;
                        mEmailFrom.setVisibility(View.VISIBLE);
                        mPhoneFrom.setVisibility(View.GONE);
                        mEmailEdt.requestFocus();
                        mEmailEdt.setSelection(mEmailEdt.getText().length());
                        mResetHintTv.setVisibility(View.VISIBLE);
                        mSendBtn.setText(R.string.send_instruction);
                        break;
                    case R.id.rbt_phone:
                        mForgotType = FORGOT_TYPE_PHONE;
                        mEmailFrom.setVisibility(View.GONE);
                        mPhoneFrom.setVisibility(View.VISIBLE);
                        mPhoneEdt.requestFocus();
                        mPhoneEdt.setSelection(mPhoneEdt.getText().length());
                        mResetHintTv.setVisibility(View.INVISIBLE);
                        mSendBtn.setText(R.string.submit);
                        if (mSendSmsAction == null) {
                            mSendSmsAction = new SendSmsAction(mActivity, mBaseView);
                            mSendSmsAction.setSmsType(Constants.SMS_TYPE_FORGOT_PASSWORD);
                            mSendSmsAction.onCreate();
                        }
                        break;
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mSendSmsAction != null) {
            mSendSmsAction.onDestroy();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mSendSmsAction != null) {
            mSendSmsAction.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imv_captcha:
                setCaptchaImv();
                break;
            case R.id.btn_send:
                if (FORGOT_TYPE_EMAIL.equals(mForgotType)) {
                    attemptForgotPasswordEmail();
                } else {
                    attemptForgotPasswordPhone();
                }
                break;
        }
    }

    private void setCaptchaImv() {
        if (mCode == null) {
            Code.Builder builder = new Code.Builder()
                    .setFontSize(mActivity, 20)
                    .setLineNumber(8)
                    .setWidth(mActivity, 90)
                    .setHeight(mActivity, 30)
                    .setPaddingLeft(mActivity, 10, 10)
                    .setPaddingTop(mActivity, 15, 10);
            mCode = builder.build();
        }
        mCaptchaImv.setImageBitmap(mCode.createBitmap());
        mCaptchaCode = mCode.getCode().toLowerCase();
    }

    private void attemptForgotPasswordEmail() {
        mEmailEdt.setError(null);
        mCaptchaEdt.setError(null);

        String email = mEmailEdt.getText().toString();
        String captcha = mCaptchaEdt.getText().toString().trim().toLowerCase();

        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(email)) {
            mEmailEdt.setError("input email");
            focusView = mEmailEdt;
            cancel = true;
        } else if (!AppUtil.isEmailValid(email)) {
            mEmailEdt.setError(getString(R.string.error_invalid_email));
            focusView = mEmailEdt;
            cancel = true;
        } else if (TextUtils.isEmpty(captcha)) {
            mCaptchaEdt.setError("input captcha");
            focusView = mCaptchaEdt;
            cancel = true;
            setCaptchaImv();
        } else if (!captcha.equals(mCaptchaCode)) {
            mCaptchaEdt.setError("captcha error");
            focusView = mCaptchaEdt;
            cancel = true;
            setCaptchaImv();
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            showProgress(true);
            forgotPassword(email);
        }
    }

    private void forgotPassword(String email) {
        getAppModel().getUserService().forgotPassword(email, new ModelCallback<Void>() {
            @Override
            public void onBeforeRequest(String urlTag) {

            }

            @Override
            public void onSuccess(Void data) {
                showProgress(false);
                findViewById(R.id.tev_check_inbox_hint).setVisibility(View.VISIBLE);
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                showProgress(false);
                if ("3311".equals(errorEvent)) {
                    mEmailEdt.setError("email账户不存在");
                    mEmailEdt.requestFocus();
                } else if ("33103".equals(errorEvent)) {
                    mEmailEdt.setError("email错误");
                    mEmailEdt.requestFocus();
                } else {
                    Toast.makeText(getAppApplication(), "error", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void attemptForgotPasswordPhone() {
        if (mSendSmsAction.checkForRegister()) {
            return;
        }
        showProgress(true);
        forgotPasswordPhone(mSendSmsAction.getSmsKey(), mSendSmsAction.getSmsCode(), mSendSmsAction.getCountryCode(), mSendSmsAction.getPhoneNum());
    }

    private void forgotPasswordPhone(String sms_key, String sms_code, String area, String phone) {
        getAppModel().getUserService().forgotPasswordPhone(area, phone, sms_key, sms_code, new ModelCallback<ResetPasswordInfo>() {
            @Override
            public void onBeforeRequest(String urlTag) {

            }

            @Override
            public void onSuccess(ResetPasswordInfo data) {
                showProgress(false);
                mActivity.startActivity(new Intent(mActivity, ResetPasswordActivity.class));
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                showProgress(false);
                if ("33105".equals(errorEvent)) {
                    Toast.makeText(getAppApplication(), "account not exists", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getAppApplication(), "error", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
